import {
  areaData
} from '../../../config/index';
import Toast from 'tdesign-miniprogram/toast/index';
import {
  baseURL
} from '../../../services/request'
import {
  addNewAgent,
  getAgentDetail,
  editAgent,
  getAgent
} from '../../../services/api/menber'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    visible: false,
    upperAgent: "",
    note: '',
    cityValue: [],
    minDate: new Date(2022, 1, 1).getTime(),
    areaData: areaData,
    areaPickerVisible: false,
    priceLevel: 20,
    invoicePics: [],
    contractPics: [],
    userList: [],
    storePics: [],
    gridConfig: {
      column: 4,
      width: 160,
      height: 160,
    },
    popvisible: false,
    isEdit: false,
    isAddPage: false,
    showSaveBtn: false,
    kid: '',
    personInfo: {
      avatar: 'https://we-retail-static-1300977798.cos.ap-guangzhou.myqcloud.com/retail-ui/components-exp/avatar/avatar-1.jpg',
      nickName: '',
      userName: "",
      gender: 0,
      userPhone: '',
      addr: '',
      agentLevel: "",
      agentType: "",
      agentUserCode: "",
      area: "",
      areaManager: "",
      city: "",
      province: "",
      contactAddr: "",
      contactName: "",
      contactPhone: "",
      contractPics: "",
      customerContext: "",
      customerSource: "",
      cxzs: "",
      empUserId: '',
      houseNo: "",
      intentionLevel: "",
      invoicePics: "",
      kid: "",
      memo: "",
      pid: "",
      priceLevel: "",
      productInNum: "",
      receiveAddr: "",
      signDate: '',
      stockNum: "",
      storePics: "",
      subdistrictBuildingNumber: "",
      subdistrictHouseNumber: "",
      subdistrictName: "",
    },
    locationState: {
      labelIndex: null,
      addressId: '',
      addressTag: '',
      cityCode: '',
      cityName: '',
      countryCode: '',
      countryName: '',
      detailAddress: '',
      districtCode: '',
      districtName: '',
      isDefault: false,
      name: '',
      phone: '',
      provinceCode: '',
      provinceName: '',
      isEdit: false,
      isOrderDetail: false,
      isOrderSure: false,
    },
    typeVisible: false,
    agentLevel: {
      value: "",
      name: ''
    },
    agentLevelIndex: -1,
    agentLevelArray: [{
        name: '省会代理',
        code: '1'
      },
      {
        name: '地市代理',
        code: '2'
      },
      {
        name: '县区代理',
        code: '3'
      },
      {
        name: '经销商',
        code: '4'
      },
    ],
    agentTypeIndex: -1,
    agentType: [{
        name: '咨询代理',
        code: 0
      },
      {
        name: '意向代理商',
        code: 1
      },
      {
        name: '正式代理商',
        code: 2
      },
    ]
  },
  // picker  change
  bindPickerChange: function (e) {
    console.log(e.currentTarget.dataset.array)
    let typeArr = e.currentTarget.dataset.array;
    console.log('picker发送选择改变，携带值为', e.detail.value);
    if (typeArr == 'agentLevelArray') {
      this.setData({
        [e.currentTarget.dataset.index]: e.detail.value,
        ["personInfo.agentLevel"]: this.data[e.currentTarget.dataset.array][e.detail.value].code
      })
    } else {
      this.setData({
        [e.currentTarget.dataset.index]: e.detail.value,
        ["personInfo.agentType"]: this.data[e.currentTarget.dataset.array][e.detail.value].code
      })
    }

  },
  // input 数据绑定
  onInputChange(e) {
    const key = e.currentTarget.dataset.key,
      value = e.detail.value;
    this.setData({
      [key]: value
    })
  },
  handleChange(e) {
    console.log(e, 'e')
    this.setData({
      priceLevel: e.detail.value,
    });
  },
  editStatus() {
    this.setData({
      isEdit: false,
      showSaveBtn: true
    })
  },
  handleCalendar() {
    this.setData({
      visible: true
    });
  },
  handleConfirm(e) {
    const {
      value
    } = e.detail;
    const format = (val) => {
      const date = new Date(val);
      const MM = (date.getMonth() + 1 < 10 ?
        '0' + (date.getMonth() + 1) :
        date.getMonth() + 1);
      const DD = date.getDate() < 10 ? '0' + date.getDate() : date.getDate();
      return `${date.getFullYear()}-${MM}-${DD}`;
    };

    this.setData({
      note: format(value),
    });
  },

  onClose({
    detail
  }) {
    console.log(detail.trigger);
  },
  // 图片上传 
  handleSuccess(e) {
    let self = this;
    let tempOrigin = [];
    const role = wx.getStorageSync('role');
    let picType = e.currentTarget.dataset.type;
    let fileList = e.detail.files;
    this.setData({
      [picType]: [...this.data[picType], ...fileList],
    });
    console.log(fileList, 'fileList')
    //  多图统一上传
    fileList.forEach((el) => {
      wx.uploadFile({
        url: `${baseURL}fileserver/pt/fileserver/action/upload`,
        filePath: el.url,
        name: 'file',
        header: {
          devType: 4,
          userId: role.userId,
          token: role.tokenId,
          appId: "crm_agent",
          authType: "agent"
        },
        success: function (result) {
          if (JSON.parse(result.data).code == 200) {
            const resourceUrl = JSON.parse(result.data).data.urlPath;
            console.log(resourceUrl);
            tempOrigin.push(resourceUrl);
            if (picType == 'invoicePics') {
              self.setData({
                "personInfo.invoicePics": [...self.data.personInfo.invoicePics, resourceUrl]
              })
            } else if (picType == 'contractPics') {
              self.setData({
                "personInfo.contractPics": [...self.data.personInfo.contractPics, resourceUrl]
              })
            } else {
              self.setData({
                "personInfo.storePics": [...self.data.personInfo.storePics, resourceUrl]
              })
            }

            // self.setData({
            //   "personInfo.avatar": resourceUrl
            // })
          }
        }
      })
    })
  },
  // 移除图片

  handleRemove(e) {
    const {
      index
    } = e.detail;
    console.log(index)
    let picType = e.currentTarget.dataset.type;
    const picTypeList = this.data[picType];
    this.data[picType].splice(index, 1);
    this.setData({
      [picType]: picTypeList,
    });
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    var pages = getCurrentPages() //获取加载的页面
    var currentPage = pages[pages.length - 1] //获取当前页面的对象
    var options = currentPage.options //如果要获取url中所带的参数可以查看options
    if (options.isEdit) {
      this.getDetailData(options);
      wx.setNavigationBarTitle({
        title: '编辑代理商',
      })
    } else {
      this.setData({
        showSaveBtn: true,
        isAddPage: true
      })
    }
    this.getAllUserList();
  },
  navToOrder() {
    //  跳转到销售单据页面
    wx.navigateTo({
      url: `/subpages/pages/saleOrder/saleOrder?orderId=${this.data.kid}`,
    })
  },
  async getAllUserList() {
    let {
      data
    } = await getAgent({});
    let index = data.findIndex((el) => el.key == this.data.personInfo.pid);
    this.setData({
      userList: data,
      upperAgent: index >= 0 ? data[index].value : ''
    })
  },
  onChange(e) {
    console.log(e.detail.value, 'e');
    this.data.userList.forEach((el) => {
      if (el.key == e.detail.value) {
        this.setData({
          popvisible: false,
          pid: e.detail.value,
          upperAgent: el.value
        })
      }
    })

  },
  async getDetailData(options) {
    let {
      code,
      data
    } = await getAgentDetail({
      kid: options.kid
    });
    let agentLevelIndex = this.data.agentLevelArray.findIndex((el) => {
      return el.code == data.agentLevel
    });
    let agentTypeIndex = this.data.agentType.findIndex((el) => {
      return el.code == data.agentType
    });

    this.setData({
      agentTypeIndex,
      agentLevelIndex,
      kid: options.kid,
      isEdit: options.isEdit,
      personInfo: data,
      // 'personInfo.storePics': data.storePics.split(','),
      // 'personInfo.invoicePics': data.invoicePics.split(','),
      // 'personInfo.contractPics': data.contractPics.split(','),
      // invoicePics: this.construstorFile(data.invoicePics.split(',')),
      // contractPics: this.construstorFile(data.contractPics.split(',')),
      // storePics: this.construstorFile(data.storePics.split(',')),
      'personInfo.storePics': data.storePics && data.storePics.split(',') || [],
      'personInfo.invoicePics': data.invoicePics && data.invoicePics.split(',') || [],
      'personInfo.contractPics': data.contractPics && data.contractPics.split(',') || [],
      invoicePics: data.invoicePics && this.construstorFile(data.invoicePics.split(',')) || [],
      contractPics: data.contractPics && this.construstorFile(data.contractPics.split(',')) || [],
      storePics: data.storePics && this.construstorFile(data.storePics.split(',')) || [],
      locationState: {
        cityCode: data.cityCode,
        cityName: data.city,
        countryCode: '',
        countryName: '',
        detailAddress: data.addr,
        districtCode: data.areaCode,
        districtName: data.area,
        isDefault: false,
        provinceCode: data.provinceCode,
        provinceName: data.province,
        isEdit: false,
        isOrderDetail: false,
        isOrderSure: false,
      },
    });
  },
  construstorFile(arr) {
    return arr.map((el) => {
      return {
        url: el,
        type: 'image',
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },
  onVerifyInputLegal() {
    const {
      name,
      phone,
      detailAddress,
      districtName
    } = this.data.locationState;
    const prefixPhoneReg = String(this.properties.phoneReg || innerPhoneReg);
    const prefixNameReg = String(this.properties.nameReg || innerNameReg);
    const nameRegExp = new RegExp(prefixNameReg);
    const phoneRegExp = new RegExp(prefixPhoneReg);

    if (!districtName || !districtName.trim()) {
      return {
        isLegal: false,
        tips: '请选择省市区信息',
      };
    }
    return {
      isLegal: true,
      tips: '添加成功',
    };
  },
  onInputValue(e) {
    const {
      item
    } = e.currentTarget.dataset;
    if (item === 'address') {
      const {
        selectedOptions = []
      } = e.detail;
      this.setData({
          'locationState.provinceCode': selectedOptions[0].value,
          'locationState.provinceName': selectedOptions[0].label,
          'locationState.cityName': selectedOptions[1].label,
          'locationState.cityCode': selectedOptions[1].value,
          'locationState.districtCode': selectedOptions[2].value,
          'locationState.districtName': selectedOptions[2].label,
          areaPickerVisible: false,
        },
        // () => {
        //   const {
        //     isLegal,
        //     tips
        //   } = this.onVerifyInputLegal();
        //   this.setData({
        //     submitActive: isLegal,
        //   });
        //   this.privateData.verifyTips = tips;
        // },
      );
    } else {
      const {
        value = ''
      } = e.detail;
      this.setData({
          [`locationState.${item}`]: value,
        },
        // () => {
        //   const {
        //     isLegal,
        //     tips
        //   } = this.onVerifyInputLegal();
        //   this.setData({
        //     submitActive: isLegal,
        //   });
        //   this.privateData.verifyTips = tips;
        // },
      );
    }
  },
  onPickArea() {
    this.setData({
      areaPickerVisible: true
    });
  },

  onConfirm(e) {
    const {
      value,
    } = e.detail;
    console.log(e.detail);
    this.setData({
        typeVisible: false,
        'agentLevel.value': value,
        "agentLevel.name": e.detail.target.name
      },
      // () => {
      //   Toast({
      //     context: this,
      //     selector: '#t-toast',
      //     message: '设置成功',
      //     theme: 'success',
      //   });
      // },
    );
  },
  onWithoutTitlePicker() {
    this.setData({
      typeVisible: true,
    })
  },
  onClose() {
    this.setData({
      typeVisible: false,
    });
  },
  onVisibleChange(e) {
    this.setData({
      popvisible: e.detail.visible,
    });
  },
  clickCell() {
    if (!this.data.isEdit) {
      this.setData({
        popvisible: true
      })
    }

  },
  onClickCell({
    currentTarget
  }) {
    const {
      dataset
    } = currentTarget;
    const {
      nickName
    } = this.data.personInfo;

    switch (dataset.type) {

      case 'avatarUrl':
        this.toModifyAvatar();
        break;

    }
  },

  save() {
    var pages = getCurrentPages() //获取加载的页面
    var currentPage = pages[pages.length - 1] //获取当前页面的对象
    var options = currentPage.options //如果要获取url中所带的参数可以查看options
    const role = wx.getStorageSync('role');
    let patten = /^[1][3,4,5,7,8,9][0-9]{9}$/;
    if (!patten.test(this.data.personInfo.contactPhone) ||
      !patten.test(this.data.personInfo.userPhone)
    ) {
      Toast({
        selector: '#t-toast',
        message: '请填写正确的手机号码',
        icon: '',
        duration: 1000,
      });
      return;
    };
    let params = {
      ...this.data.personInfo,
      invoicePics: this.data.personInfo.invoicePics && this.data.personInfo.invoicePics.join(','),
      contractPics: this.data.personInfo.contractPics && this.data.personInfo.contractPics.join(','),
      storePics: this.data.personInfo.storePics && this.data.personInfo.storePics.join(','),
      province: this.data.locationState.provinceName,
      provinceCode: this.data.locationState.provinceCode,
      city: this.data.locationState.cityName,
      cityCode: this.data.locationState.cityCode,
      area: this.data.locationState.districtName,
      areaCode: this.data.locationState.districtCode,
      signDate: this.note,
      empUserId: role.userId,
      pid: this.data.pid
    };
    if (options.isEdit) {
      //  编辑
      this.editData(params)
    } else {
      // 新增
      this.saveData(params)
    }
  },
  async editData(params) {
    let res = await editAgent({
      ...params,
      kid: this.data.kid
    });
    if (res.code == '200') {
      wx.navigateTo({
        url: '/subpages/pages/allTeams/allTeams',
      })
    }
  },

  async saveData(params) {
    let res = await addNewAgent(params);
    if (res.code == '200') {
      wx.navigateTo({
        url: '/subpages/pages/allTeams/allTeams',
      })
    }
  },

  async toModifyAvatar() {
    let self = this;
    try {
      const tempFilePath = await new Promise((resolve, reject) => {
        wx.chooseImage({
          count: 1,
          sizeType: ['compressed'],
          sourceType: ['album', 'camera'],
          success: (res) => {
            const {
              path,
              size
            } = res.tempFiles[0];
            if (size <= 10485760) {
              resolve(path);
            } else {
              reject({
                errMsg: '图片大小超出限制，请重新上传'
              });
            }
          },
          fail: (err) => reject(err),
        });
      });
      const tempUrlArr = tempFilePath.split('/');
      // const tempFileName = tempUrlArr[tempUrlArr.length - 1];
      const role = wx.getStorageSync('role');
      wx.uploadFile({
        url: `${baseURL}fileserver/pt/fileserver/action/upload`,
        filePath: tempFilePath,
        name: 'file',
        header: {
          devType: 4,
          userId: role.userId,
          token: role.tokenId,
          appId: "crm_agent",
          authType: "agent"
        },
        success: function (result) {
          if (JSON.parse(result.data).code == 200) {
            const resourceUrl = JSON.parse(result.data).data.urlPath
            self.setData({
              "personInfo.avatar": resourceUrl
            })
          }
        }
      })


    } catch (error) {
      if (error.errMsg === 'chooseImage:fail cancel') return;

    }
  },
})